(function($) {
	
	$.fn.isLoggedIn = function(){
		
		return $(this).each(function(){
			
			var $setReminderWrap= $('#course_status .set_reminder_wrap'),
				$setMobileBtn	= $('#course_status .set_mobile_btn'),
				$addReminderWrap= $('#course_status .add_reminder_wrap'),
				$addReminder	= $('#course_status .add_reminder'),
				$cancelReminder	= $('#course_status .cancel_reminder'),
				$mobile			= $('#course_status .mobile'),
				courseUniqueId	= $('#courseUniqueId').val(),
				isOwner			= $('#isOwner').val();
				
			var detectFlash = function() {
				if($.flash.hasVersion(10.2)){
					location.href= '' + $.global.getContextPath() + '/room/' + courseUniqueId + '/auth';
				}
				else{
					if($.ua.browser.extend =='sougou'){
						location.href= '' + $.global.getContextPath() + '/flash/webkit/update/' + courseUniqueId;
					}
					else if($.ua.engine.webkit){
						location.href= '' + $.global.getContextPath() + '/flash/webkit/update/' + courseUniqueId;
					}
					else if($.ua.browser.firefox){
						location.href= '' + $.global.getContextPath() + '/flash/firefox/update/' + courseUniqueId;
					}
					else{
						location.href= '' + $.global.getContextPath() + '/flash/ie/update/' + courseUniqueId;
					}
				}
				return false;
			};

			var isValidMobile	= function(value) {
					var length = value.length,
						mobile = /^(1(([35][0-9])|(47)|[8][0126789]))\d{8}$/,
						$mobileErrorWrap = $('#sms_reminder .mobile_error_wrap');
						$mobileErrorOverlay = $('#sms_reminder .mobile_error_overlay');
						$mobileError = $('#sms_reminder .mobile_error');
					
					if(!(length == 11 && mobile.test(value))){
						$mobileError.text('手机号码不正确');
						$mobileErrorOverlay.css({background: '#f9d0d0', opacity: 0.9});
						$mobileErrorWrap.css({opacity: 0}).show().animate({opacity: 1}, 400, function() {
							$(this).delay(500).animate({opacity: 0}, 300, function() {
								$(this).hide();
							});
						});
					}
					
					return length == 11 && mobile.test(value);
				};

			$('input').placeholder();
			
			//设置短信提醒
			$setMobileBtn.click(function() {
				$(this).hide();
				$addReminderWrap.show();
			});
			
			$cancelReminder.click(function() {
				$addReminderWrap.hide();
				$setMobileBtn.show();
				$mobile.blur();
			});
			
			$addReminder.click(function() {
				if($.trim($mobile.val()) === ''){
					$mobile.val('').css('background','#f5cfcf')
						.animate({opacity: 0.3}, function(){
							$mobile.css('background','#ffffff')
								.animate({opacity: 1});
					});
				} else {
					if(!isValidMobile($mobile.val())) {
						return false;
					}
					
					$.ajax({
						async	: false,
						url		: [$.global.getContextPath(), '/course/', courseUniqueId, '/sms'].join(''),
						type	: 'post',
						dataType: 'json',
						data	: {mobile: $mobile.val()},
						beforeSend: function(xhr) {
					        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
					    },
						success: function(json) {
							if(json.success) {
								if($('#attend_lists .add_course_schedule')[0]) {
									$.wokaobox.open({
										href		: [$.global.getContextPath(), '/course/', courseUniqueId, '/schedule'].join(''),
										width		: 632,
										height		: 290,
										type		: 'iframe',
										modal		: true,
										beforeShow	: function(){
											
											$setReminderWrap.animate({visibility: 'hidden'}, function() {
												$(this).empty().append('<p class="has_reminder_tip">您已设置短信提醒</p>');
											});
											
											if(isOwner !== 'true') {
												
												$('#attend_lists .add_course_schedule, #attend_lists .empty_tip').hide();
												$('#add_schedule').slideUp();
						
												var $enrollNum = $('.enroll_num')
												  , enrollNum = parseInt($enrollNum.text());
												
												$enrollNum.text(enrollNum + 1);
												
												$.ajax({
													async	: false,
													cache	: false,
													url		: [$.global.getContextPath(), '/', courseUniqueId, '/display/enroll/page/1'].join(''),
													type	: 'get',
													dataType: 'html',
													beforeSend: function (xhr) {
												        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
												    },
													success: function(html){
														$('.attend_user_list').replaceWith(html);
													}
												});
											}
											
											$.global.getNewMessages();
										}
									});
								} else {
									$setReminderWrap.empty().append('<p class="has_reminder_tip">您已设置短信提醒</p>');
								}
							}
						}
					});
					return false;
				}
			});
			
			//进教室
			$('#enter_form, #pre_enter_form').live('submit',function(){
				$.ajax({
					async:false,
					url:$(this).attr('action'),
					type:'post',
					dataType:'json',
					context:$(this),
					beforeSend: function (xhr) {
						 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
					},
					success:function(json){
						
						if(json.roomIsFull){
							$('#status_tip').hide();
							$(this).prepend('<div id="status_tip"><p>此教室已满，请稍后再试!</p></div>');
							return false;
						} else if(json.classIsOver){
							$(this).prepend('<div id="status_tip"><p>课程已结束！</p></div>')
								   .delay(300).fadeIn(500, function(){
										location.reload();
								   });
							return false;
						} else{
							detectFlash();
						}
					}
				});
				return false;
			});
			
			//收藏课程、取消收藏
			$('#favorite').click(function(){
				var that = $(this)
				  , isAdd = that.hasClass('add_favor')
				  , courseUniqueId = $('#courseUniqueId').val()
				  , addOrRemoveFovorHref;
				
				if(isAdd){
					addOrRemoveFovorHref = [$.global.getContextPath(), '/course/', courseUniqueId, '/favor'].join('');
				} else {
					addOrRemoveFovorHref = [$.global.getContextPath(), '/course/', courseUniqueId, '/unfavor'].join('');
				}
				
				$.ajax({
					async:false,
					url:addOrRemoveFovorHref,
					type:'post',
					dataType:'json',
					beforeSend: function (xhr) {
						 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
					},
					success:function(json) {
						if(json.success){
							$('span', that).toggle();
							if(isAdd){
								that.removeClass('add_favor').attr('title', '取消收藏');
							} else {
								that.addClass('add_favor').attr('title', '添加收藏');
							}
						}
					}
				});
				return false;
			});
			
			//关注讲师、取消关注
			$('#add_or_remove_follow').isAddOrRemoveFollow({
				followBtnCommonClass: 'follow_btn',
				addFollowBtnClass: 'add_follow_btn',
				removeFollowBtnClass: 'remove_follow_btn',
				onAnonymous: function(){
					$('#anonymous-login').click();
					return false;
				},
				onException: function(){
					return false;
				}
			});

			//报名缴费
			$("#pay_confirm").wokaobox({
				'width'	: 620,
				'height': 380,
				'type'	: 'iframe',
				'href'	: $("#pay_confirm").attr('action')
			});
			
			//我想参加（设置备忘）
			$('#attend_lists .add_course_schedule, #course_status .add_course_schedule, #add_schedule .add_course_schedule')
			.attr('href', [$.global.getContextPath(), '/course/', courseUniqueId, '/schedule'].join(''))
			.wokaobox({
				type		: 'iframe',
				width		: 632,
				height		: 290,
				modal		: true,
				beforeShow	: function(){
					
					if(isOwner !== '' + true){
						
						$('#attend_lists .add_course_schedule, #attend_lists .empty_tip').remove();
						$('#add_schedule').slideUp();

						var $enrollNum = $('.enroll_num')
						  , enrollNum = parseInt($enrollNum.text());
						
						$enrollNum.text(enrollNum + 1);
						
						$.ajax({
							async:false,
							url:[$.global.getContextPath(), '/', courseUniqueId, '/display/enroll/page/1'].join(''),
							type:'get',
							dataType:'html',
							cache: false,
							beforeSend: function (xhr) {
						        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
						    },
							success:function(html){
								$('.attend_user_list').replaceWith(html);
							}
						});
					}
					
					$.global.getNewMessages();
				},
				afterClose: function(){
					location.href = location.href;
				}
			})
			.bind('click', function(){
				if($('#course_status').find('form:first').hasClass('pay_confirm')){
					$('#pay_now').click();
					return false;
				}
				if(!$(this).hasClass('add_course_schedule')){
					return false;
				}
			});
		});
	};
})(jQuery);